package mfuny.ggongal.admin.mygift;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.ad.AdDao;
import mfuny.ggongal.admin.ad.AdDetail;
import mfuny.ggongal.admin.ad.MissionDetail;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.json.JsonCreater;
import mfuny.ggongal.admin.play.PlayDao;

import org.json.simple.JSONObject;

import com.ibatis.sqlmap.client.SqlMapClient;

public class MyGiftService {
	SqlMapClient sqlMapper;
	JsonCreater jc;
	
	public MyGiftService() throws Exception {
		sqlMapper = Server.getSqlMapper();
		jc = new JsonCreater();
	}
	
	//당첨자 내 경품 등록.
	public int setMyGift(PlayDao myPlay, int myRank) throws Exception {
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", myPlay.getAd_no());
		Date days = AdDetail.ad_getDateForSGame(ad);
		int giftPrice = 0;
		
		HashMap<String, Object> gift = MissionDetail.getGiftDetailByRank_mission(ad.getMission(), myRank);
		
		MyGiftDao myGift = new MyGiftDao();
		myGift.setAd_no(myPlay.getAd_no());
		myGift.setUser_id(myPlay.getId());
		myGift.setDays(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(days));
		myGift.setGifttype((String)gift.get("giftType"));
		
		if(myGift.getGifttype().equals("현물")) {
			myGift.setGift_id((String)gift.get("giftId"));
			giftPrice = (Integer)sqlMapper.queryForObject("gift_selectPriceById", myGift.getGift_id());
			
		} else if(myGift.getGifttype().equals("모바일상품권")) {
			myGift.setGiftcard(Integer.parseInt((String)gift.get("giftId")));
			giftPrice = (Integer)sqlMapper.queryForObject("card_selectPriceByNo", myGift.getGiftcard());
		}
		
		if(giftPrice >= 50000) {
			myGift.setNeedtax(1);
		} else {
			myGift.setNeedtax(0);
		}
		
		myGift.setIswin(1);
		
		int result = sqlMapper.update("myGift_insert", myGift);
		Object obj = null;
		if(result > 0){
			obj = sqlMapper.queryForObject("myGift_selectFinalNoById", myGift.getUser_id());
		}
		
		result = obj != null ? (Integer)obj : -1;
		return result;
	}
	
	//당첨자 내 경품 등록.
	public int setMyGift(HashMap<String, Object> params, int myRank)	throws Exception {
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", (Integer) params.get("ad_no"));
		Date days = AdDetail.ad_getDateForSGame(ad);
		int giftPrice = 0;

		HashMap<String, Object> gift = MissionDetail.getGiftDetailByRank_mission(ad.getMission(), myRank);

		MyGiftDao myGift = new MyGiftDao();
		myGift.setAd_no((Integer) params.get("ad_no"));
		myGift.setUser_id((String) params.get("user_id"));
		myGift.setDays(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(days));
		myGift.setGifttype((String) gift.get("giftType"));

		if (myGift.getGifttype().equals("현물")) {
			myGift.setGift_id((String) gift.get("giftId"));
			giftPrice = (Integer) sqlMapper.queryForObject("gift_selectPriceById", myGift.getGift_id());
			
		} else if (myGift.getGifttype().equals("모바일상품권")) {
			myGift.setGiftcard(Integer.parseInt((String) gift.get("giftId")));
			giftPrice = (Integer) sqlMapper.queryForObject("card_selectPriceByNo", myGift.getGiftcard());
		}

		if (giftPrice >= 50000) {
			myGift.setNeedtax(1);
		} else {
			myGift.setNeedtax(0);
		}
		
		myGift.setIswin(1);

		int hasIt = (Integer) sqlMapper.queryForObject("myGift_hasIt", myGift);
		int result = 0;
		if (hasIt <= 0) {
			result = sqlMapper.update("myGift_insert", myGift);
		}

		Object obj = null;
		if (result > 0 || hasIt > 0) {
			obj = sqlMapper.queryForObject("myGift_selectTheMyGift", myGift);
		}

		result = obj != null ? (Integer) obj : -1;
		return result;
	}
	
	//스페셜게임 실패한 mygift 등록.
	public int setMyGiftForFail(HashMap<String, Object> params) throws Exception {
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", (Integer) params.get("ad_no"));
		HashMap<String, Object> gift = MissionDetail.getGiftDetailByRank_mission(ad.getMission(), Integer.parseInt(ad.getMission().split("/")[2].split(",")[0]));
		
		MyGiftDao myGift = new MyGiftDao();
		myGift.setAd_no((Integer)params.get("ad_no"));
		myGift.setDays(String.valueOf(params.get("days")));
		myGift.setUser_id((String)params.get("user_id"));
		myGift.setIswin(0);
		myGift.setGifttype((String)gift.get("giftType"));
		
		int giftPrice = 0;
			
		if ( myGift.getGifttype() != null && myGift.getGifttype().equals("현물")) {
			myGift.setGift_id((String) gift.get("giftId"));
			giftPrice = (Integer) sqlMapper.queryForObject("gift_selectPriceById", myGift.getGift_id());
			
		} else if ( myGift.getGifttype() != null && myGift.getGifttype().equals("모바일상품권")) {
			myGift.setGiftcard(Integer.parseInt((String) gift.get("giftId")));
			giftPrice = (Integer) sqlMapper.queryForObject("card_selectPriceByNo", myGift.getGiftcard());
		}

		if (giftPrice >= 50000) {
			myGift.setNeedtax(1);
		} else {
			myGift.setNeedtax(0);
		}
		
		myGift.setIswin(0);

		int hasIt = (Integer) sqlMapper.queryForObject("myGift_hasIt", myGift);
		
		int result = 0;
		if (hasIt <= 0) {
			result = sqlMapper.update("myGift_insert", myGift);
		}
		
		Object obj = null;
		if (result > 0 || hasIt > 0) {
			obj = sqlMapper.queryForObject("myGift_selectTheMyGift", myGift);
		}

		result = obj != null ? (Integer) obj : -1;
		return result;
	}
	
	//경품을 받을지 말지 여부 결정.
	@SuppressWarnings("unchecked")
	public int setIsReceive(int mygift_no, int receive) throws Exception {
		MyGiftDao myGift = new MyGiftDao();
		HashMap<String, Object> myGiftClass = (HashMap<String, Object>) sqlMapper.queryForObject("myGift_selectByNo", mygift_no);
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", myGiftClass.get("ad_no"));
		
		myGift.setMygift_no(mygift_no);
		
		if(receive > 0) {
			myGift.setIsreceive(1);
		}else {
			myGift.setIsreceive(0);
		}
		
		int result = 0;
		try{
			sqlMapper.startTransaction();
			result = sqlMapper.update("myGift_updateReceive", myGift);
			if(ad.getService().equals("special") ) {
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("user_id", myGiftClass.get("user_id"));
				paramMap.put("ad_no", myGiftClass.get("ad_no"));
				paramMap.put("days", myGiftClass.get("days"));
				result = sqlMapper.update("spec_updateByEtcs", paramMap);
				if(result <= 0) {
					throw new Exception();
				}
			}
			
			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "setIsReceive");
		}finally{
			sqlMapper.endTransaction();
		}
		
		return result;
	}
	
	//경품받을경우 추가 입력.
	@SuppressWarnings({ "unchecked" })
	public JSONObject setMyGift2(HashMap<String, Object> params) throws Exception {
		JSONObject json = new JSONObject();
		try{
			sqlMapper.startTransaction();
			//주소지 업데이트.
			HashMap<String, Object> myGift = (HashMap<String, Object>) sqlMapper.queryForObject("myGift_selectByNo", params.get("mygift_no"));
			int result = 0;
			if(myGift.get("gifttype").equals("현물")) {
				result = sqlMapper.update("user_addressUpdate", params);
				if(result <= 0) {
					throw new Exception();
				}
			}
			
			//내경품정보 추가입력.
			result = sqlMapper.update("myGift_updateMyGift2", params);
			if(result <= 0) {
				throw new Exception();
			}
			
			//스페셜게임인 경우 체킹 끝.
			AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", myGift.get("ad_no"));
			if(ad.getService().equals("special")) {
				HashMap<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("user_id", myGift.get("user_id"));
				paramMap.put("ad_no", myGift.get("ad_no"));
				paramMap.put("days", myGift.get("days"));
				
				result = sqlMapper.update("spec_updateByEtcs", paramMap);
				if(result <= 0) {
					throw new Exception();
				}
			}
			
			sqlMapper.commitTransaction();
			json.put("responseCode", result);
			
		}catch(Exception e){
			Debug.toDebugFile(e, "setMyGift2");
			json.put("responseCode", 0);
		}finally{
			sqlMapper.endTransaction();
		}
		return json;
	}
	
	//현재 특정 내경품 정보 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject getMyGiftByNo(int mygift_no) throws Exception {
		HashMap<String, Object> myGift = (HashMap<String, Object>)sqlMapper.queryForObject("myGift_selectByNo", mygift_no);
		myGift.put("days", "" + myGift.get("days"));
		return jc.getJsonByMap(myGift);
	}
}
